import { computed } from 'vue';

export function useModelWrapper(props, emit, name = 'modelValue') {
  return computed({
    get: () => props[name],
    set: (value) => emit(`update:${name}`, value)
  });
}

export function useMove(el) {
  el.style.position = 'fixed';
  let oL, oT, oLeft, oTop;
  if (el != null) {
    const maxW = document.body.clientWidth - el.offsetWidth;
    const maxH = document.body.clientHeight - el.offsetHeight;
    const defaultEvent = function (e) {
      // e.preventDefault();
    };
    el.addEventListener(
      'touchstart',
      function (e) {
        const ev = e || window.event;
        const touch = ev.targetTouches[0];
        oL = touch.clientX - el.offsetLeft;
        oT = touch.clientY - el.offsetTop;
        document.addEventListener('touchmove', defaultEvent, { passive: false });
        el.addEventListener(
          'touchmove',
          function (e) {
            const ev = e || window.event;
            const touch = ev.targetTouches[0];
            oLeft = touch.clientX - oL;
            oTop = touch.clientY - oT;
            if (oLeft < 0) {
              oLeft = 0;
            } else if (oLeft >= maxW) {
              oLeft = maxW;
            }
            if (oTop < 0) {
              oTop = 0;
            } else if (oTop >= maxH) {
              oTop = maxH;
            }
            el.style.left = oLeft + 'px';
            el.style.top = oTop + 'px';
          },
          { passive: false }
        );
        el.addEventListener('touchend', function () {
          document.removeEventListener('touchmove', defaultEvent);
        });
      },
      { passive: false }
    );
  }
}
